define(function(repire, exports, module) {
    'use strict';
    var menuUtil = {};

    (function() {

        var ALL_OPTIONS = {};
        var hide_timer;
        var currentButton;

        //全局监听关闭按钮
        $('body').on('click.delegatemenu', function(e) {
            var target = $(e.target);
            window.clearTimeout(hide_timer);
            if ($(target).closest('[isdelegatemenusbutton="true"]').size() > 0 || target.attr('isdelegatemenusbutton') == 'true') {
                return;
            } else {
                $('body').find('[menuId]').attr('menuId','');
                me._close();
            }
        });
        //全局监听菜单点击
        $('body').on('click.delegatemenuclick', 'div[isdelegatemenu]', function(e) {
            var target = $(e.target);
            var menu = target.closest('[isdelegatemenu]');
            var menuId = menu.attr('id');
            var opt = ALL_OPTIONS[menuId];
            var itemSel = opt.itemSel ? opt.itemSel : 'li';
            var item;
            if ($(target).closest(itemSel).size() > 0) item = $(target).closest(itemSel);
            if (target.is(itemSel)) item = target;
            if (opt.onSelect) opt.onSelect(e, currentButton, item);
        });

        var me = menuUtil = {
            connect: function(opt) {
                var container
                if (opt.container) container = opt.container;
                if (opt.containerSel) container = $(opt.containerSel);
                if (container.data('delegatemenuinited' + opt.buttonSel)) return; //已绑定过
                var containerId = container.attr('id');

                containerId = containerId ? containerId : container.uniqueId();
                var menuCount = $.isNumeric(container.data('delegatemenucount')) ? parseInt(container.data('delegatemenucount')) + 1 : 0;
                container.data('delegatemenucount', menuCount)
                container.attr('has_delegatemenu', true);
                var menuId = containerId + '_delegatemenu_' + menuCount;

                ALL_OPTIONS[menuId] = opt;

                //缓存容器和菜单id的关系，主要是防止一开始按钮并不存在
                var info = container.data('delegatemenuinfo');
                info = info ? info : {};
                info[opt.buttonSel] = menuId;
                container.data('delegatemenuinfo', info);
                container.data('delegatemenuinited' + opt.buttonSel, true);
                //代理事件
                container.on('click.' + menuId, opt.buttonSel, function(e) {
                    var btn = $(this);
                    //window.setTimeout(function(){
                    window.clearTimeout(hide_timer);
                    btn.attr('isdelegatemenusbutton', 'true');
                    var container = btn.closest('[has_delegatemenu]');
                    var info = container.data('delegatemenuinfo');
                    for (var sel in info) {
                        if (btn.is(sel)) {
                            var menuId = info[sel];
                            var opt = ALL_OPTIONS[menuId];
                            var parentElem = opt.menuParent ? opt.menuParent : '#crm-panel';
                            if ($('#' + menuId).size() == 0) {
                                $(parentElem).append('<div id="' + menuId + '" isdelegatemenu="true" style="display:none;position:absolute;z-index:999999999;">' + (opt.menuHtml ? opt.menuHtml : '') + '</div>')
                            }
                            if ($('#' + menuId).css('display') == 'none') {
                                me._open(btn, menuId);
                            } else {
                                me._close(menuId);
                                if(btn.attr('menuId') != menuId){
                                    clearAll();
                                    me._open(btn, menuId);
                                    btn.attr('menuId', menuId);
                                }
                            }
                        }
                    }
                    //}, 1);

                });

                function clearAll(){
                    container.find(opt.buttonSel).attr('menuId', '');
                }
            },
            _open: function(btn, menuId) {
                var me = this;
                var opt = ALL_OPTIONS[menuId];

                me._close();

                var button = btn;
                var menu = $('#' + menuId);
                var showmenu = true;
                if ($.isFunction(opt.beforeOpen)) {
                    var result = (opt.beforeOpen)(button, '#' + menuId);
                    if (result === false) showmenu = false; //可以在beforeOpen中，组织菜单弹出
                }
                if (!showmenu) return;
                menu.show();
                if (opt.onOpen)(opt.onOpen)(button, '#' + menuId);
                var position = opt.position ? opt.position : {
                    my: 'center top',
                    at: 'right bottom'
                };
                menu.css({
                    left: 0,
                    top: 0
                }).position({
                    of: button,
                    my: position.my,
                    at: position.at
                });
                if ($.isFunction(opt.afterOpen))(opt.afterOpen)(button, '#' + menuId);
                currentButton = button;
            },
            _delayClose: function(ms) {
                if (typeof ms == 'undefined') ms = 150;
                var me = this;
                hide_timer = window.setTimeout(function() {
                    me._close();
                }, ms);
            },
            _close: function() {
                var me = this;
                $('[isdelegatemenu]').hide();
                //if(opt.onClose)(opt.onClose)();
                currentButton = null;
                //这一个操作怎么能从外面传进来呢？
                $('.xsyvisible').removeClass('xsyvisible');

            }
        }


        exports = menuUtil;
    })();

    return menuUtil;
});
